<template>
  <div class="containers">
    <div class="container">
      <div class="handle-box">

        <el-select v-model="take" @change="getData" placeholder="请选择类型" size="small" class="mr10">
          <el-option v-for="item in navlists" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="status" @change="getData" placeholder="请选择类型" size="small" class="mr10">
          <el-option v-for="item in paylist" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <el-date-picker class="mr10" v-model="value2" type="datetimerange" :picker-options="pickerOptions"
          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" size="small" align="right"
          @change="changeTime">
        </el-date-picker>
        <el-input v-model="keyword" placeholder="订单号/用户电话/收货人" class="handle-input mr10" size="small"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="getData" class="mr10" size="small">搜索</el-button>
        <el-button type="primary" @click="exportExcel" class="mr10" size="small">导出</el-button>
      </div>

      <el-table :data="tableData" class="table" ref="multipleTable" header-cell-class-name="table-header"
        @selection-change="handleSelectionChange" v-loading="loading" id="out-table">
        <el-table-column prop="order_id" label="订单号"></el-table-column>
        <!-- <el-table-column prop="user.nickname" label="购买用户"></el-table-column> -->
        <el-table-column label="商品图">
          <template slot-scope="scope">
            <div style="display: flex; align-items: center">
              <el-image class="table-td-thumb" :src="getimg(scope.row)[0]"
                :preview-src-list="getimg(scope.row)"></el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品名称">
          <template slot-scope="scope">
            <div style="display: flex; align-items: center">
              <p>{{ getname(scope.row) }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品数量">
          <template slot-scope="scope">
            <div style="display: flex; align-items: center">
              <p>{{ getquantity(scope.row) }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="商品价格"></el-table-column>
        <el-table-column prop="store_name" label="店铺名"></el-table-column>
        <el-table-column label="收货人" align="center">
          <template slot-scope="scope">
            {{ scope.row.take == 2 ? scope.row.name : '无' }}
          </template>
        </el-table-column>
        <el-table-column label="收货人电话" align="center">
          <template slot-scope="scope">
            {{ scope.row.mobile }}
          </template>
        </el-table-column>

        <el-table-column label="支付方式" align="center">
          <template slot-scope="scope">
            {{
              ['茶花', '微信', '支付宝', '银行卡', 'DD'][scope.row.pay_type]
            }}
          </template>
        </el-table-column>
        <el-table-column label="取餐方式" align="center">
          <template slot-scope="scope">
            {{ ['堂食', '打包外带', '外送'][scope.row.take] }}
          </template>
        </el-table-column>
        <el-table-column label="订单状态" align="center">
          <template slot-scope="scope">
            {{
              ["更新取餐码", "err", "err1", "出餐完成", "配送中", "已完成", "出餐失败退款", "err2", "err3", "部分退款"][
              scope.row.status
              ]
            }}
          </template>
        </el-table-column>
        <el-table-column label="下单时间" align="center">
          <template slot-scope="scope">
            {{ parseDateTime(scope.row.CreatedAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="handleEdit(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handlePageChange"
          :current-page="query.pageIndex" :page-sizes="[20, 30, 40, 50]" :page-size="query.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="pageTotal">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import excel from "../../../utils/excel.js";
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
  name: "basetable",
  data() {
    return {
      money: 0,
      take: -1,
      partition: [],
      query: {
        pageIndex: 1,
        pageSize: 20,
      },
      status: -1,
      upload: "",
      editVisible: false,
      pageTotal: 0,
      imageUrl: "",
      videoUrl: "",
      type: 0,
      take: -1,
      navlist: [
        { id: 0, name: "全部" },
        { id: 1, name: "待发货" },
        { id: 2, name: "待收货" },
        { id: 3, name: "完成" },
        { id: 4, name: "已完成1" },
        { id: 5, name: "售后" },
      ],
      navlists: [
        { id: -1, name: "全部" },
        { id: 0, name: "堂食" },
        { id: 1, name: "打包外带" },
        { id: 2, name: "外送" },
      ],
      paylist: [
        { id: -1, name: "全部" },
        { id: 0, name: "更新取餐码" },
        { id: 3, name: "出餐完成" },
        { id: 4, name: "配送中" },
        { id: 5, name: "已完成" },
        { id: 6, name: "出餐失败退款" },
        { id: 9, name: "部分退款" },
      ],
      pay_type: -1,
      keyword: "",
      loading: false,
      tableData: [
      ],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      value2: "",
      start_time: "",
      end_time: "",
    };
  },
  created() {
    this.getData();

  },
  methods: {



    exportExcel() {
      var token = localStorage.getItem('admin_token_sys')
      //导出
      this.$http({
        url: this.mainurl + 'api/openapi/kfc/getOrder/?code=1',
        method: 'get',
        responseType: 'blob',
        params: {
          pay_type: this.pay_type,
          start_time: this.start_time,
          end_time: this.end_time,
          take: this.take,
          page: this.query.pageIndex,
          size: this.query.pageSize,
          state: this.state,
          keyword: this.keyword,
          code: 1,
          source: 0,
        },

        headers: {
          'Content-Type': 'application/json',
          token: token
        }
      }).then(res => {
        console.log(res);
        try {
          FileSaver.saveAs(
            new Blob([res.data], { type: "application/octet-stream;charset=utf-8" }), "订单.xlsx")
        } catch (e) {
          if (typeof console !== "undefined") console.log(e, res.data);
        }
      })



    },
    //修改size值
    handleSizeChange(val) {
      this.query.pageSize = val;
      this.getData();
    },

    //获取数据
    getData() {
      this.loading = true;
      this.request("api/openapi/kfc/getOrder/", "get", {
        start_time: this.start_time,
        end_time: this.end_time,
        page: this.query.pageIndex,
        size: this.query.pageSize,
        keyword: this.keyword,
        take: this.take,
        status: this.status,
      }).then((res) => {
        console.log(res, "res")
        this.tableData = res.data.data;
        this.pageTotal = res.data.total;
      });
      this.loading = false;

    },
    // 发货
    handleEdit(e) {
      this.$router.push({
        path: "/order/kfcDetails",
        query: { id: e.order_id },
      });
    },
    cancel() {
      this.getData();
    },

    // 删除操作
    handleDelete(index, row) {
      // 二次确认删除
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning",
      }).then(() => {
        this.request("admin/order/", "delete", { ID: row.ID }).then((res) => {
          if (res.errno == 0) {
            this.$message.success(res.errmsg);
            this.tableData.splice(index, 1);
            this.getData();
          } else {
            this.$message.error(res.errmsg);
          }
        });
      });
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, "pageIndex", val);
      this.getData();
    },
    changeTime(e) {
      //时间
      console.log(e);
      try {
        this.start_time = this.formatDate(e[0]);
        this.end_time = this.formatDate(e[1]);
      } catch (error) {
        this.start_time = "";
        this.end_time = "";
      }

      this.getData();
    },
    formatTen(num) {
      return num > 9 ? num + "" : "0" + num;
    },
    formatDate(date) {
      var date = new Date(date);
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      var hour = date.getHours();
      var minute = date.getMinutes();
      var second = date.getSeconds();
      return (
        year +
        "-" +
        this.formatTen(month) +
        "-" +
        this.formatTen(day) +
        " " +
        this.formatTen(hour) +
        ":" +
        this.formatTen(minute) +
        ":" +
        this.formatTen(second)
      );
    },
    //获取图片
    getimg(row) {

      let goods_detail = JSON.parse(row.goods_detail)
      let arr = []
      goods_detail.forEach((item) => {
        let img = ""
        img = item.img
        arr.push(img)
      })
      return arr
    },
    //获取名字
    getname(row) {

      let goods_detail = JSON.parse(row.goods_detail)
      let str = ""

      goods_detail.forEach((item) => {
        str += item.name + '/'
      })

      return str
    },
    //获取数量
    getquantity(row) {
      let goods = JSON.parse(row.goods)
      let goods_detail = JSON.parse(row.goods_detail)
      let str = goods_detail.length
      return str
    },
    //时间
    parseDateTime(dateTimeStr) {
      // 创建一个新的 Date 对象
      const date = new Date(dateTimeStr);

      // 获取年份、月份、日期、小时、分钟和秒
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要加1
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      // 返回格式化后的字符串
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
  },
};
</script>

<style scoped>
.container {
  padding: 20px;
}

.el-upload--text {
  width: 200px !important;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;

  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  /* width: 100px; */
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100%;
  height: 178px;
  display: block;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 60px;
  height: 60px;
}

/* 设置分页按钮样式 */
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.table-td-thumb {
  margin: 0 !important;
}

.namelist {
  margin-left: 10px;
}

/* #file{
  width:0px;
  height: 10px;
  opacity: 0;
} */
</style>
